

import { engine } from "../../engine/engine";
import { LocalSocketProto } from "./LocalSocketProto";
import { ILocalSocket } from "./ILocalSocket";
import { LocalSocketFactory } from "./LocalSocketFactory";


export class LocalSocketServer implements ILocalSocket {

    protected onmessage: { [proto: string]: (err: string, data: any) => void } = {};

    post(result: net.ResData): void {
        if (this.onmessage[result.protoId]) {
            this.onmessage[result.protoId](null, result)
        }
    }

    push(retName: string, retData: any): void {
        let pushMessage: net.PushData = { protoId: retName, data: retData }
        pushMessage.protoId = retName;
        this.post(pushMessage);
    }

    send(reqData: net.ReqData, callback: (err: string, data: any) => void): void {

        let ins: LocalSocketProto = LocalSocketFactory.builder(reqData.protoId)
        if (ins) {
            ins.setService(this)
            this.onmessage[reqData.protoId] = callback;
            ins.action(reqData, (code: number, resData: any) => {
                let result: net.ResData = { code: code, data: resData, session: reqData.session, protoId: reqData.protoId }
                this.post(result)
            })
        } else {
            engine.error("消息未实现", reqData.protoId);
        }
    }

}